import { ScrollView, StyleSheet, Text, View, Image } from 'react-native'
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { IS_IPHONEX, ScaleS, ScaleT, HEIGHT } from 'src/utils/ScreenUtil'
import DefaultImage from 'src/components/image/DefaultImage'
import { defaultPortraitGray, getUserAvatorLocalB, getUserAvatorLocalC } from 'src/utils/ConfigUtil'
import CustomImage from 'src/components/image/CustomImage'
import CustomButton from 'src/components/button/CustomButton'
import { showImageViewerModal } from 'src/utils/ModalUtil'

const imgMaxWidth = 200
export default class DialogueComponent extends PureComponent {
  static defaultProps = {
    msgArray: [],
    isPageB: false
  }

  static propTypes = {
    msgArray: PropTypes.array,
    friendInfo: PropTypes.object,
    loginInfoState: PropTypes.object,
    userId: PropTypes.number,
    onLayout: PropTypes.func,
    onContentSizeChange: PropTypes.func,
    onScroll: PropTypes.func,
    onTouchStart: PropTypes.func,
    onTouchMove: PropTypes.func,
    onTouchEnd: PropTypes.func,
    scrollViewRef: PropTypes.func,
    isPageB: PropTypes.bool,
    selToID: PropTypes.number,
    style: PropTypes.oneOfType([PropTypes.object, PropTypes.array])
  }

  constructor (props) {
    super(props)
    this.state = {}
  }

  _scrollViewRef = (ref) => {
    const { scrollViewRef } = this.props
    scrollViewRef && scrollViewRef(ref)
  }

  render () {
    const { style, msgArray, onLayout, onContentSizeChange, onScroll, onTouchStart, onTouchMove, onTouchEnd } = this.props
    return (
      <ScrollView
        style={[styles.container].concat(style)}
        ref={this._scrollViewRef}
        onLayout={onLayout}
        onContentSizeChange={onContentSizeChange}
        scrollEventThrottle={1}
        onScroll={onScroll}
        onTouchStart={onTouchStart}
        onTouchMove={onTouchMove}
        onTouchEnd={onTouchEnd}
      >
        {!!msgArray && !!msgArray.length > 0 && msgArray.map((item, index) => {
          return this._chatItem(item, index)
        })}
      </ScrollView>
    )
  }

  _chatItem = (item, index) => {
    const { friendInfo, loginInfoState, userId, isPageB, selToID } = this.props
    const userAvatar = friendInfo.avatar
    return !item.isSelf ? (
      <View
        key={index}
        id={`chat${index}`}
        style={styles.chatContainer}
      >
        {!!item.displayTimeHeader && (
          <View style={styles.chatTimeContainer}>
            <View style={styles.chatTimeContent}>
              <Text style={styles.chatTime}>
                {item.displayTimeHeader}
              </Text>
            </View>
          </View>
        )}

        <View style={[styles.chatItem, styles.chatItemOther]}>
          <DefaultImage
            style={styles.headerImg}
            source={{ uri: userAvatar }}
            errorSource={isPageB ? getUserAvatorLocalC(friendInfo.gender, selToID) : getUserAvatorLocalB(friendInfo.gender)}
            defaultSource={defaultPortraitGray}
          />
          <View style={styles.chatValue}>
            {this._returnChatValue({ item, type: item.type })}
          </View>
        </View>
      </View>
    ) : (
      <View
        key={index}
        id={`chat${index}`}
        style={styles.chatContainer}
      >
        {!!item.displayTimeHeader && (
          <View style={styles.chatTimeContainer}>
            <View style={styles.chatTimeContent}>
              <Text style={styles.chatTime}>
                {item.displayTimeHeader}
              </Text>
            </View>
          </View>
        )}

        <View style={[styles.chatItem, styles.chatItemMine]}>
          <View style={[styles.chatValue, styles.chatValueRight]}>
            {this._returnChatValue({ item, type: item.type })}
          </View>
          <DefaultImage
            style={[styles.headerImg, styles.headerImgRight]}
            defaultSource={defaultPortraitGray}
            errorSource={isPageB ? getUserAvatorLocalB(loginInfoState.gender) : getUserAvatorLocalC(
              loginInfoState.gender,
              userId
            )}
            source={{ uri: loginInfoState.avatar }}
          />
        </View>
      </View>
    )
  }

  _returnChatValue = ({ item, type }) => {
    const { value } = item
    switch (type) {
      case 'text':
        return <Text style={styles.chatItemText}>{value}</Text>
      case 'image':
        const { value: uri, width, height } = item
        let textStyle = {}
        if (width > imgMaxWidth) {
          // 大于imgMaxWidth 则进行缩放
          textStyle = { width: ScaleS(imgMaxWidth), height: ScaleS(height * imgMaxWidth / width) }
        } else {
          textStyle = { width: ScaleS(width), height: ScaleS(height) }
        }
        return <CustomButton onPress={this._previewImg} params={{ uri }}>
          <CustomImage
            style={[styles.chatItemImg, textStyle]}
            source={{ uri }}
          />
        </CustomButton>
      default:
        return <Text style={styles.chatItemText}>{value}</Text>
    }
  }

  _previewImg = ({ uri }) => {
    // 预览图片
    this.imgageViewerModal = showImageViewerModal({
      onClose: this._closeImageViewerModal,
      images: [{
        url: uri
      }]
    })
  }

  _closeImageViewerModal = () => {
    if (this.imgageViewerModal) {
      this.imgageViewerModal.close()
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingVertical: ScaleS(20),
    paddingHorizontal: ScaleS(20)
  },
  headerImg: {
    width: ScaleS(35),
    height: ScaleS(35),
    borderRadius: ScaleS(18),
    marginRight: ScaleS(12),
    resizeMode: 'cover'
  },
  headerImgRight: {
    marginRight: 0,
    marginLeft: ScaleS(14)
  },
  chatContainer: {
    flexDirection: 'column',
    marginBottom: ScaleS(30)
  },
  chatTimeContainer: {
    width: '100%',
    height: ScaleS(20),
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: ScaleS(30)
  },
  chatTimeContent: {
    height: ScaleS(20),
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#D8D8D8',
    borderRadius: ScaleS(5),
    paddingHorizontal: ScaleS(4)
  },
  chatTime: {
    fontSize: ScaleT(11),
    color: '#FFFFFF'
  },
  chatItem: {
    flexDirection: 'row',
    alignItems: 'center'
    // width: ScaleS(375)
  },
  chatItemOther: {
    justifyContent: 'flex-start'
  },
  chatItemMine: {
    justifyContent: 'flex-end'
  },
  chatValue: {
    maxWidth: ScaleS(243),
    backgroundColor: '#fff',
    borderRadius: ScaleS(10),
    paddingVertical: ScaleS(8),
    paddingHorizontal: ScaleS(15)
  },
  chatValueRight: {
    backgroundColor: '#FFE400'
  },
  chatItemText: {
    fontSize: ScaleT(14),
    lineHeight: ScaleS(18),
    color: '#3C3C3C'
  },
  chatItemImg: {
    maxWidth: ScaleS(200),
    resizeMode: 'contain'
  },
  bottomContainer: {},
  sendContainer: {
    width: ScaleS(375),
    paddingHorizontal: ScaleS(10),
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#F3F3F3',
    paddingBottom: ScaleS(IS_IPHONEX ? 40 : 10)
  },
  commonIcon: {
    width: ScaleS(54),
    height: ScaleS(30),
    borderRadius: ScaleS(3),
    justifyContent: 'center',
    alignItems: 'center'
  },
  commonIconText: {
    color: '#fff',
    fontSize: ScaleT(14)
  }
})
